<template>
  <el-row>
    <el-col :span="12">
      <el-card class="chart-container">
        <div
          slot="header"
          class="clearfix"
          style="display:flex;align-items:center;"
        >
          <b style="font-size:16px;">决策信息及作物日生长数据统计分析</b>
          <el-cascader
            v-model="growthArr"
            :options="fieldPlants"
            clearable
            filterable
            style="margin-left:auto;width:300px;"
            @change="handleChange"
          />
        </div>
        <ve-histogram
          :height="chartHeight"
          :data="plantDetailDailyData"
          :extend="chartExtend"
          :settings="chartSettings"
        />
        <div class="h24" />
        <div class="h24" />
        <v-chart
          ref="cropDailyChart"
          :auto-rezise="true"
          :option="cropDailyData"
          class="chart"
          @click="handleClick"
        />
      </el-card>
    </el-col>
    <el-col :span="12">
      <el-card
        class="chart-container ml0"
        style="padding:0"
      >
        <div class="weather-container">
          <el-descriptions
            title="气象信息"
            :column="4"
            border
            label-class-name="labelClass"
            content-class-name="contentClass"
          >
            <template slot="title">气象信息 —— {{ date }}</template>
            <el-descriptions-item label="最高温度">{{ getFloatAttr('temp_high',weatherDaily) }} ℃</el-descriptions-item>
            <el-descriptions-item label="最低温度">{{ getFloatAttr('temp_low',weatherDaily) }} ℃</el-descriptions-item>
            <el-descriptions-item label="平均温度">{{ getFloatAttr('temp_avg',weatherDaily) }} ℃</el-descriptions-item>
            <el-descriptions-item label="相对湿度">{{ getFloatAttr('humidity',weatherDaily) }}% RH</el-descriptions-item>
            <el-descriptions-item label="降雨量">{{ getFloatAttr('rainfall',weatherDaily) }} mm</el-descriptions-item>
            <el-descriptions-item label="平均风速">{{ getFloatAttr('wind_spd',weatherDaily) }} m/s</el-descriptions-item>
            <el-descriptions-item label="太阳辐射">{{ getFloatAttr('radiation',weatherDaily) }} MJ/m²d</el-descriptions-item>
            <el-descriptions-item label="日照时数">{{ getFloatAttr('sunshine_acc',weatherDaily) }} h</el-descriptions-item>
          </el-descriptions>
        </div>
        <div class="h24" />
        <div class="sqz-container">
          <el-descriptions
            title="相对含水率"
            :column="4"
            border
            label-class-name="labelClass"
            content-class-name="contentClass"
          >
            <template slot="title">相对含水率 —— {{ date }}</template>
            <el-descriptions-item label="10cm">{{ getFloatAttr('M1',fieldSensorDaily) }} %</el-descriptions-item>
            <el-descriptions-item label="30cm">{{ getFloatAttr('M2',fieldSensorDaily) }} %</el-descriptions-item>
            <el-descriptions-item label="50cm">{{ getFloatAttr('M3',fieldSensorDaily) }} %</el-descriptions-item>
            <el-descriptions-item label="70cm">{{ getFloatAttr('M4',fieldSensorDaily) }} %</el-descriptions-item>
          </el-descriptions>
        </div>
        <div class="h24" />
        <div class="sqz-container">
          <el-descriptions
            title="作物生长信息"
            :column="4"
            border
            label-class-name="labelClass"
            content-class-name="contentClass"
          >
            <template slot="title">作物生长信息 —— {{ date }}</template>
            <el-descriptions-item label="kc">{{ getFloatAttr('kc',cropDaily,3) }}</el-descriptions-item>
            <el-descriptions-item label="灌溉上限">{{ getFloatAttr('wc_max',cropDaily,0) }} %</el-descriptions-item>
            <el-descriptions-item label="灌溉下限">{{ getFloatAttr('wc_min',cropDaily,0) }} %</el-descriptions-item>
            <el-descriptions-item label="ETc">{{ getFloatAttr('water_consum',cropDaily,2) }} mm</el-descriptions-item>
          </el-descriptions>
        </div>
        <div class="h24" />
        <div class="sqz-container">
          <el-descriptions
            title="决策信息"
            :column="3"
            border
            label-class-name="labelClass"
            content-class-name="contentClass"
          >
            <template slot="title">决策信息 —— {{ date }}</template>
            <!-- <template slot="extra">
              <el-button type="primary" icon="el-icon-document">查看详情</el-button>
            </template> -->
            <el-descriptions-item label="决策类型">水量平衡法</el-descriptions-item>
            <el-descriptions-item label="累积耗水量">{{ getFloatAttr('amount',plantDetailDaily) }} mm</el-descriptions-item>
            <!-- <el-descriptions-item label="实施状态">
              <el-tag
                v-if="plantDetailDaily && plantDetailDaily.do_at"
                type="success"
              >已实施</el-tag>
              <el-tag
                v-else
                type="danger"
              >未实施</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="操作">
              <el-button
                type="primary"
                size="mini"
                @click="doNow"
              >去实施</el-button>
            </el-descriptions-item> -->
          </el-descriptions>
        </div>
        <div class="h24" />
        <el-tabs
          v-model="activeName"
          type="card"
        >
          <el-tab-pane
            label="气象日数据"
            name="first"
          >
            <div>
              <ve-line
                v-if="activeName === 'first'"
                :height="chartHeight"
                :data="weatherDailyData"
                :extend="chartExtend2"
                :settings="chartSettings"
              />
            </div>
          </el-tab-pane>
          <el-tab-pane
            label="墒情日数据"
            name="second"
          >
            <div>
              <ve-line
                v-if="activeName === 'second'"
                :height="chartHeight"
                :data="censusData.field_sensor_data"
                :extend="chartExtend2"
                :settings="chartSettings"
              />
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </el-col>
    <el-dialog
      v-el-drag-dialog
      :title="title"
      :visible.sync="dialogVisible"
      append-to-body
      width="1080px"
      @close="closeDialog"
    >
      <main-form :form-data="formData" />
    </el-dialog>
  </el-row>
</template>

<script>
import VChart from 'vue-echarts'
import { getOne } from '@/api/census'
import { getOne as getPlantDetail } from '@/api/plantDetail'
import { getFloatAttr, getCurrentDate } from '@/utils'
import { mapGetters } from 'vuex'
import MainForm from '../policy/index/component/main-form'
export default {
  name: 'Statistics',
  components: {
    VChart,
    MainForm
  },
  data() {
    return {
      title: '决策详情',
      dialogVisible: false,
      formData: {},
      growth: 1,
      growthArr: [],
      growthes: [],
      activeName: 'first',
      chartSettings: {},
      height: 'calc(100vh - 273px)',
      chartHeight: '360px',
      chartExtend: {
        series: {
          showSymbol: false,
          stack: 'intelirri',
          barMaxWidth: 20
        },
        color: ['#fc8452', '#409eff', '#67c23a'],
        grid: {
          left: '2%',
          right: '2%',
          bottom: '0%',
          top: '18%',
          containLabel: true
        }
      },
      chartExtend2: {
        series: {
          showSymbol: false
        },
        grid: {
          left: '2%',
          right: '2%',
          bottom: '0%',
          top: '18%',
          containLabel: true
        }
      },
      censusData: {},
      weatherDailyData: [],
      cropDaily: {},
      weatherDaily: {},
      fieldSensorDaily: {},
      plantDetailDaily: {},
      date: '',
      plantDetailDailyData: {},
      cropDailyData: {}
    }
  },
  computed: {
    ...mapGetters(['cropGrowthes', 'fields', 'project']),
    field() {
      const res = this.fields.filter((val) => {
        return +val.project_id === +this.project.id
      })
      return res[0] || {}
    },
    plantId() {
      if (this.field.plants) {
        return this.field.plants.slice(-1)[0].id || 0
      }
      return 0
    },
    fieldPlants() {
      const fields = this.fields.filter((val) => {
        return +val.project_id === +this.project.id
      })
      const res = []
      fields.forEach((item) => {
        res.push({
          value: item.plant.id,
          label: [item.name, item.plant.plant_year, item.plant.crop.name].join('-'),
          children: item.plant.cropGrowthes.map((val) => {
            return {
              value: val.id,
              label: val.stage_name
            }
          })
        })
      })
      return res
    }
  },
  watch: {
    // cropGrowthes: {
    //   handler(newVal) {
    //     this.growthes = newVal.filter((val) => {
    //       return +val.plant_id === this.plantId
    //     })
    //     this.growth = this.getCurrentGrowth()
    //   },
    //   immediate: true,
    //   deep: true
    // },
    date: {
      handler(newVal) {
        this.weatherDaily = this.censusData.weather_daily_data.filter(val => {
          return val.gdate === newVal
        })[0]
        this.cropDaily = this.censusData.crop_daily_data.filter(val => {
          return val.gdate === newVal
        })[0]
        this.fieldSensorDaily = this.censusData.field_sensor_data.rows.filter(val => {
          return val.gdate === newVal
        })[0]
        this.plantDetailDaily = this.censusData.plant_detail_daily_data.rows.filter(val => {
          return val.created_at === newVal
        })[0]
      },
      deep: true
    }
  },
  mounted() {
    window.addEventListener('resize', this.resizeChart)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeChart)
  },
  created() {
    this.growthArr = [this.fieldPlants[0]['value'], this.fieldPlants[0]['children'][0]['value']]
    this.getCurrentGrowth()
    this.getOne(this.plantId)
  },
  methods: {
    handleChange(val) {
      this.getOne()
    },
    closeDialog() {
      this.getOne(this.plantId)
    },
    async doNow() {
      const { data } = await getPlantDetail(this.censusData.plant_detail_daily.id)
      this.formData = data
      this.dialogVisible = true
    },
    changeGrowth(val) {
      this.getOne(this.plantId)
    },
    getCurrentGrowth() {
      const now = getCurrentDate()
      const growthes = this.cropGrowthes.filter((val) => {
        return +val.plant_id === +this.growthArr[0]
      })
      const growthes_filter = growthes.filter((val) => {
        return val.stage_start <= now && val.stage_end > now
      })
      if (growthes_filter[0] && growthes_filter[0].id) {
        this.growthArr[1] = growthes_filter[0].id
      }
    },
    async getOne() {
      const plant_id = this.growthArr[0]
      const crop_growth_id = this.growthArr[1]
      const { data } = await getOne({ plant_id, crop_growth_id })
      this.censusData = data
      this.weatherDailyData = this.getWeatherDailyData()
      this.cropDailyData = this.getCropDailyData(data.crop_daily_data)
      this.plantDetailDailyData = data.plant_detail_daily_data
      this.cropDaily = data.crop_daily
      this.weatherDaily = data.weather_daily
      this.fieldSensorDaily = data.field_sensor_daily
      this.plantDetailDaily = data.plant_detail_daily
      this.date = data.date
    },
    getWeatherDailyData() {
      const fields = [
        { namekey: 'gdate', name: '日期' },
        { namekey: 'temp_avg', name: '平均温度(℃)' },
        // { namekey: 'temp_low', name: '最低温度(℃)' },
        // { namekey: 'temp_high', name: '最高温度(℃)' },
        { namekey: 'rainfall', name: '降雨量(mm)' },
        { namekey: 'wind_spd', name: '风速(m/s)' },
        { namekey: 'radiation', name: '辐射(W/m2)' },
        { namekey: 'humidity', name: '相对湿度(%RH)' },
        // { namekey: 'pressure', name: '大气压(kPa)' },
        { namekey: 'et0', name: 'et0' },
        { namekey: 'temp_acc', name: '积温(℃)' },
        { namekey: 'sunshine_acc', name: '日照时长(h)' }
      ]

      return {
        columns: fields.map(val => val.name),
        rows: this.censusData.weather_daily_data.map((item) => {
          const temp = {}
          fields.forEach((citem) => {
            temp[citem.name] = item[citem.namekey]
          })
          return temp
        })
      }
    },
    getCropDailyData(cropDailyData) {
      const res = {
        grid: {
          top: '15%',
          left: '2%',
          right: '2%',
          bottom: '8%',
          containLabel: true
        },
        title: {},
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['ETc(mm)', '土壤含水率(%)', 'kc', '湿润层深度(cm)', '灌溉上限(%)', '灌溉下限(%)']
        },
        color: ['#fc8452', '#73c0de', '#fac858', '#5470c6', '#91cc75', '#ee6666'],
        calculable: true,
        xAxis: [
          {
            type: 'category',
            data: cropDailyData.map(val => val.gdate.substr(0, 10))
          }
        ],
        yAxis: [
          {
            type: 'value',
            splitLine: { // 网格线
              lineStyle: {
                type: 'dashed' // 设置网格线类型 dotted：虚线 solid:实线
              },
              show: true // 隐藏或显示
            }
          }
        ],
        series: [
          {
            name: 'ETc(mm)',
            type: 'line',
            smooth: true,
            showSymbol: false,
            data: cropDailyData.map(val => (+val.water_consum).toFixed(2)),
            markLine: {
              data: [{ type: 'average', name: 'Avg' }]
            },
            lineStyle: {
              color: '#fc8452'
            }
          },
          {
            name: '土壤含水率(%)',
            type: 'line',
            smooth: true,
            showSymbol: false,
            data: cropDailyData.map(val => (+val.water_content).toFixed(2)),
            markLine: {
              data: [{ type: 'average', name: 'Avg' }]
            },
            lineStyle: {
              color: '#73c0de'
            }
          },
          {
            name: 'kc',
            type: 'line',
            smooth: true,
            showSymbol: false,
            data: cropDailyData.map(val => (+val.kc).toFixed(3)),
            markLine: {
              data: [{ type: 'average', name: 'Avg' }]
            },
            lineStyle: {
              color: '#fac858'
            }
          },
          {
            name: '湿润层深度(cm)',
            type: 'line',
            smooth: true,
            showSymbol: false,
            data: cropDailyData.map(val => val.soil_depth),
            markLine: {
              data: [{ type: 'average', name: 'Avg' }]
            },
            lineStyle: {
              color: '#5470c6'
            }
          },
          {
            name: '灌溉上限(%)',
            type: 'line',
            smooth: true,
            showSymbol: false,
            data: cropDailyData.map(val => val.wc_max),
            markLine: {
              data: [{ type: 'average', name: 'Avg' }]
            },
            lineStyle: {
              color: '#91cc75'
            }
          },
          {
            name: '灌溉下限(%)',
            type: 'line',
            smooth: true,
            showSymbol: false,
            data: cropDailyData.map(val => val.wc_min),
            markLine: {
              data: [{ type: 'average', name: 'Avg' }]
            },
            lineStyle: {
              color: '#ee6666'
            }
          }
        ]
      }

      return res
    },
    resizeChart() {
      if (this.$refs && this.$refs.cropDailyChart) {
        this.$refs.cropDailyChart.resize()
      }
    },
    handleClick(params) {
      this.$message.success(params.name)
      this.date = params.name
    },
    getFloatAttr(name, data, precision = 2) {
      return getFloatAttr(name, data, precision)
    }
  }
}
</script>

<style lang="scss" scoped>
.chart-container {
  height: calc(100vh - 74px);
  margin: 12px;
  padding: 12px;
}
.ml0 {
  margin-left: 0;
}
.chart {
  height: calc(50vh - 80px);
}
.weather-chart,
.sqz-chart {
  height: 280px;
}
</style>
